/*
 * settings.c
 *
 * Created: 27.03.2013 13:25:46
 *  Author: Timmo
 */ 
#include <avr/eeprom.h>
#include <avr/pgmspace.h>
#include <util/delay.h>

#include "battery.h"
#include "display.h"
#include "settings.h"

const char str_firmware_version[] PROGMEM = "0.97";
const char str_firmware_date[] PROGMEM = __DATE__ ;
const char str_fimrware_time[] PROGMEM = __TIME__ ;

const firmware_information_t firmware_information  ={str_firmware_version,str_firmware_date, str_fimrware_time};
    
#define SETTING_DEFAULTS {0,0,0,30,200,1,0,0,0,0,0,0xFF}

settings_t mt_settings;

settings_t  default_settings EEMEM = SETTING_DEFAULTS;
const settings_t  default_settings_pgm PROGMEM = SETTING_DEFAULTS;


uint8_t identify_PCB_Revision(){
	uint8_t revision;
	PORTA.DIRSET = (1<<PIN5); //2.5V LDO Enable Pin
	PORTA.OUTSET = (1<<PIN5); //Enable 2.5V
	_delay_ms(10); //wait for stabilize
	
	//enable Pulldown to check if PA0 is floating or not
	PORTA.PIN0CTRL = PORT_OPC_PULLDOWN_gc;
	if(PORTA.IN & (1<<PIN0))
		revision = 10;
	else
		revision = 9;
	
	PORTA.OUTCLR = (1<<PIN5);
	PORTA.DIRCLR = (1<<PIN5);
	PORTA.PIN0CTRL = 0;
	
	return revision;
	
}



uint8_t	load_settings(settings_t *settings_struct){
	eeprom_read_block(settings_struct,(uint8_t*)&default_settings,sizeof(settings_t));
    /* If something went wrong with the EEPROM load the defaults from flash 
     * and write it back to EEPROM 
     */
    if(settings_struct->camera_type > 10 || settings_struct->PCB_Revision == 0xFF){
		
        memcpy_P(settings_struct, &default_settings_pgm,sizeof(settings_t));
		settings_struct->PCB_Revision = identify_PCB_Revision();
        eeprom_write_block(settings_struct,(uint8_t*)&default_settings,sizeof(settings_t));
    }
     
    set_charge_current();
	
	return 0;
}

uint8_t save_settings(settings_t *settings_struct){
	eeprom_write_block(settings_struct,(uint8_t*)&default_settings,sizeof(settings_t));
	lcd_setfontsize(font_medium);
	clr_display();
	tiny_printp(6,2,PSTR("Einstellungen im"));
	tiny_printp(6,3,PSTR("EEPROM gespeichert!"));
	show_display();
	_delay_ms(1000);
	set_charge_current();
	return 0;
}